package com.example.guethe.fireanalysisapp.util;



import com.example.guethe.fireanalysisapp.DApplication;
import com.example.guethe.fireanalysisapp.data.beans.User;

import cn.droidlover.xdroidmvp.cache.SharedPref;

/**
 * 登录助手类
 * 1 检测是否登录 <br>
 * 2 设置用户缓存 <br>
 * 3 从缓存读取用户信息 <br>
 * @author spzhao
 */

public class LoginHelper {

    private static User mUser;

    public static User getUser() {
        if (mUser == null) {
            String id,name,tel,email,accessToken;
            SharedPref sharedPref = SharedPref.getInstance(DApplication.getAppContext());
            id = sharedPref.getString("id",null);
            email = sharedPref.getString("email",null);
            name = sharedPref.getString("name",null);
            tel = sharedPref.getString("tel",null);
            accessToken=sharedPref.getString("accessToken",null);

            /**
             * 未找到mobile记录，表示未登录
             */
            if (name == null) {
                return null;
            }

            mUser = new User();
            mUser.setId(id);
            mUser.setEmail(email);
            mUser.setTel(tel);
            mUser.setName(name);
            mUser.setAccessToken(accessToken);


            return mUser;
        }
        return mUser;
    }

    public static void saveUser (User user) {
        if (user != null) {
            SharedPref sharedPref = SharedPref.getInstance(DApplication.getAppContext());
            sharedPref.putString("id",user.id);
            sharedPref.putString("email",user.email);
            sharedPref.putString("name",user.name);
            sharedPref.putString("tel",user.tel);
            sharedPref.putString("accessToken",user.accessToken);
            mUser = user;
        }
    }

    public static Boolean isLogin () {
        mUser = getUser();
        return mUser != null;
    }

    public static void logout () {
        SharedPref sharedPref = SharedPref.getInstance(DApplication.getAppContext());
        sharedPref.remove("id");
        sharedPref.remove("email");
        sharedPref.remove("name");
        sharedPref.remove("tel");
        sharedPref.remove("accessToken");
        mUser = null;
    }
}
